home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / wx / py / shell.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  37KB  |  1,160 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. __author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
  5. __cvsid__ = '$Id: shell.py 46528 2007-06-18 19:09:00Z RD $'
  6. __revision__ = '$Revision: 46528 $'[11:-2]
  7. import wx
  8. from wx import stc
  9. import keyword
  10. import os
  11. import sys
  12. import time
  13. from buffer import Buffer
  14. import dispatcher
  15. import editwindow
  16. import frame
  17. from pseudo import PseudoFileIn
  18. from pseudo import PseudoFileOut
  19. from pseudo import PseudoFileErr
  20. from version import VERSION
  21. sys.ps3 = '<-- '
  22. NAVKEYS = (wx.WXK_END, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_UP, wx.WXK_DOWN, wx.WXK_PRIOR, wx.WXK_NEXT)
  23.  
  24. class ShellFrame(frame.Frame, frame.ShellFrameMixin):
  25.     name = 'Shell Frame'
  26.     revision = __revision__
  27.     
  28.     def __init__(self, parent = None, id = -1, title = 'PyShell', pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.DEFAULT_FRAME_STYLE, locals = None, InterpClass = None, config = None, dataDir = None, *args, **kwds):
  29.         frame.Frame.__init__(self, parent, id, title, pos, size, style)
  30.         frame.ShellFrameMixin.__init__(self, config, dataDir)
  31.         if size == wx.DefaultSize:
  32.             self.SetSize((750, 525))
  33.         
  34.         intro = 'PyShell %s - The Flakiest Python Shell' % VERSION
  35.         self.SetStatusText(intro.replace('\n', ', '))
  36.         self.shell = Shell(parent = self, id = -1, introText = intro, locals = locals, InterpClass = InterpClass, startupScript = self.startupScript, execStartupScript = self.execStartupScript, *args, **kwds)
  37.         self.shell.setStatusText = self.SetStatusText
  38.         self.shell.SetFocus()
  39.         self.LoadSettings()
  40.  
  41.     
  42.     def OnClose(self, event):
  43.         if self.shell.waiting:
  44.             if event.CanVeto():
  45.                 event.Veto(True)
  46.             
  47.         else:
  48.             self.SaveSettings()
  49.             self.shell.destroy()
  50.             self.Destroy()
  51.  
  52.     
  53.     def OnAbout(self, event):
  54.         title = 'About PyShell'
  55.         text = 'PyShell %s\n\n' % VERSION + 'Yet another Python shell, only flakier.\n\n' + "Half-baked by Patrick K. O'Brien,\n" + 'the other half is still in the oven.\n\n' + 'Shell Revision: %s\n' % self.shell.revision + 'Interpreter Revision: %s\n\n' % self.shell.interp.revision + 'Platform: %s\n' % sys.platform + 'Python Version: %s\n' % sys.version.split()[0] + 'wxPython Version: %s\n' % wx.VERSION_STRING + '\t(%s)\n' % ', '.join(wx.PlatformInfo[1:])
  56.         dialog = wx.MessageDialog(self, text, title, wx.OK | wx.ICON_INFORMATION)
  57.         dialog.ShowModal()
  58.         dialog.Destroy()
  59.  
  60.     
  61.     def OnHelp(self, event):
  62.         frame.ShellFrameMixin.OnHelp(self, event)
  63.  
  64.     
  65.     def LoadSettings(self):
  66.         if self.config is not None:
  67.             frame.ShellFrameMixin.LoadSettings(self)
  68.             frame.Frame.LoadSettings(self, self.config)
  69.             self.shell.LoadSettings(self.config)
  70.         
  71.  
  72.     
  73.     def SaveSettings(self, force = False):
  74.         if self.config is not None:
  75.             frame.ShellFrameMixin.SaveSettings(self)
  76.             if self.autoSaveSettings or force:
  77.                 frame.Frame.SaveSettings(self, self.config)
  78.                 self.shell.SaveSettings(self.config)
  79.             
  80.         
  81.  
  82.     
  83.     def DoSaveSettings(self):
  84.         if self.config is not None:
  85.             self.SaveSettings(force = True)
  86.             self.config.Flush()
  87.         
  88.  
  89.  
  90. HELP_TEXT = '* Key bindings:\nHome              Go to the beginning of the command or line.\nShift+Home        Select to the beginning of the command or line.\nShift+End         Select to the end of the line.\nEnd               Go to the end of the line.\nCtrl+C            Copy selected text, removing prompts.\nCtrl+Shift+C      Copy selected text, retaining prompts.\nAlt+C             Copy to the clipboard, including prefixed prompts.\nCtrl+X            Cut selected text.\nCtrl+V            Paste from clipboard.\nCtrl+Shift+V      Paste and run multiple commands from clipboard.\nCtrl+Up Arrow     Retrieve Previous History item.\nAlt+P             Retrieve Previous History item.\nCtrl+Down Arrow   Retrieve Next History item.\nAlt+N             Retrieve Next History item.\nShift+Up Arrow    Insert Previous History item.\nShift+Down Arrow  Insert Next History item.\nF8                Command-completion of History item.\n                  (Type a few characters of a previous command and press F8.)\nCtrl+Enter        Insert new line into multiline command.\nCtrl+]            Increase font size.\nCtrl+[            Decrease font size.\nCtrl+=            Default font size.\nCtrl-Space        Show Auto Completion.\nCtrl-Alt-Space    Show Call Tip.\nShift+Enter       Complete Text from History.\nCtrl+F            Search\nF3                Search next\nCtrl+H            "hide" lines containing selection / "unhide"\nF12               on/off "free-edit" mode\n'
  91.  
  92. class ShellFacade:
  93.     name = 'Shell Interface'
  94.     revision = __revision__
  95.     
  96.     def __init__(self, other):
  97.         d = self.__dict__
  98.         d['other'] = other
  99.         d['helpText'] = HELP_TEXT
  100.  
  101.     
  102.     def help(self):
  103.         self.write(self.helpText)
  104.  
  105.     
  106.     def __getattr__(self, name):
  107.         if hasattr(self.other, name):
  108.             return getattr(self.other, name)
  109.         else:
  110.             raise AttributeError, name
  111.  
  112.     
  113.     def __setattr__(self, name, value):
  114.         if self.__dict__.has_key(name):
  115.             self.__dict__[name] = value
  116.         elif hasattr(self.other, name):
  117.             setattr(self.other, name, value)
  118.         else:
  119.             raise AttributeError, name
  120.  
  121.     
  122.     def _getAttributeNames(self):
  123.         list = [
  124.             'about',
  125.             'ask',
  126.             'autoCallTip',
  127.             'autoComplete',
  128.             'autoCompleteAutoHide',
  129.             'autoCompleteCaseInsensitive',
  130.             'autoCompleteIncludeDouble',
  131.             'autoCompleteIncludeMagic',
  132.             'autoCompleteIncludeSingle',
  133.             'callTipInsert',
  134.             'clear',
  135.             'pause',
  136.             'prompt',
  137.             'quit',
  138.             'redirectStderr',
  139.             'redirectStdin',
  140.             'redirectStdout',
  141.             'run',
  142.             'runfile',
  143.             'wrap',
  144.             'zoom']
  145.         list.sort()
  146.         return list
  147.  
  148.  
  149.  
  150. class Shell(editwindow.EditWindow):
  151.     name = 'Shell'
  152.     revision = __revision__
  153.     
  154.     def __init__(self, parent, id = -1, pos = wx.DefaultPosition, size = wx.DefaultSize, style = wx.CLIP_CHILDREN, introText = '', locals = None, InterpClass = None, startupScript = None, execStartupScript = True, *args, **kwds):
  155.         editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
  156.         self.wrap()
  157.         if locals is None:
  158.             import __main__ as __main__
  159.             locals = __main__.__dict__
  160.         
  161.         self.stdin = sys.stdin
  162.         self.stdout = sys.stdout
  163.         self.stderr = sys.stderr
  164.         if InterpClass == None:
  165.             Interpreter = Interpreter
  166.             import interpreter
  167.         else:
  168.             Interpreter = InterpClass
  169.         self.reader = PseudoFileIn(self.readline, self.readlines)
  170.         self.reader.input = ''
  171.         self.reader.isreading = False
  172.         self.interp = Interpreter(locals = locals, rawin = self.raw_input, stdin = self.reader, stdout = PseudoFileOut(self.writeOut), stderr = PseudoFileErr(self.writeErr), *args, **kwds)
  173.         self.buffer = Buffer()
  174.         self.autoCompleteKeys = self.interp.getAutoCompleteKeys()
  175.         self.promptPosStart = 0
  176.         self.promptPosEnd = 0
  177.         self.more = False
  178.         self.history = []
  179.         self.historyIndex = -1
  180.         self.noteMode = 0
  181.         self.MarkerDefine(0, stc.STC_MARK_ROUNDRECT)
  182.         self.searchTxt = ''
  183.         self.Bind(wx.EVT_CHAR, self.OnChar)
  184.         self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  185.         self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)
  186.         self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI)
  187.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Cut()), id = wx.ID_CUT)
  188.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Copy()), id = wx.ID_COPY)
  189.         self.Bind((wx.EVT_MENU,), (lambda evt: self.CopyWithPrompts()), id = frame.ID_COPY_PLUS)
  190.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Paste()), id = wx.ID_PASTE)
  191.         self.Bind((wx.EVT_MENU,), (lambda evt: self.PasteAndRun()), id = frame.ID_PASTE_PLUS)
  192.         self.Bind((wx.EVT_MENU,), (lambda evt: self.SelectAll()), id = wx.ID_SELECTALL)
  193.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Clear()), id = wx.ID_CLEAR)
  194.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Undo()), id = wx.ID_UNDO)
  195.         self.Bind((wx.EVT_MENU,), (lambda evt: self.Redo()), id = wx.ID_REDO)
  196.         self.waiting = False
  197.         self.Bind(wx.EVT_IDLE, self.OnIdle)
  198.         self.showIntro(introText)
  199.         self.setBuiltinKeywords()
  200.         self.setLocalShell()
  201.         if execStartupScript:
  202.             if startupScript is None:
  203.                 startupScript = os.environ.get('PYTHONSTARTUP')
  204.             
  205.             self.execStartupScript(startupScript)
  206.         else:
  207.             self.prompt()
  208.         wx.CallAfter(self.ScrollToLine, 0)
  209.  
  210.     
  211.     def clearHistory(self):
  212.         self.history = []
  213.         self.historyIndex = -1
  214.         dispatcher.send(signal = 'Shell.clearHistory')
  215.  
  216.     
  217.     def destroy(self):
  218.         del self.interp
  219.  
  220.     
  221.     def setFocus(self):
  222.         self.SetFocus()
  223.  
  224.     
  225.     def OnIdle(self, event):
  226.         if self.waiting:
  227.             time.sleep(0.05)
  228.         
  229.         event.Skip()
  230.  
  231.     
  232.     def showIntro(self, text = ''):
  233.         if text:
  234.             self.write(text)
  235.         
  236.         
  237.         try:
  238.             if self.interp.introText:
  239.                 if text and not text.endswith(os.linesep):
  240.                     self.write(os.linesep)
  241.                 
  242.                 self.write(self.interp.introText)
  243.         except AttributeError:
  244.             pass
  245.  
  246.  
  247.     
  248.     def setBuiltinKeywords(self):
  249.         import __builtin__ as __builtin__
  250.         __builtin__.close = __builtin__.exit = __builtin__.quit = 'Click on the close button to leave the application.'
  251.  
  252.     
  253.     def quit(self):
  254.         self.write('Click on the close button to leave the application.')
  255.  
  256.     
  257.     def setLocalShell(self):
  258.         self.interp.locals['shell'] = ShellFacade(other = self)
  259.  
  260.     
  261.     def execStartupScript(self, startupScript):
  262.         if startupScript and os.path.isfile(startupScript):
  263.             text = 'Startup script executed: ' + startupScript
  264.             self.push('print %r; execfile(%r)' % (text, startupScript))
  265.             self.interp.startupScript = startupScript
  266.         else:
  267.             self.push('')
  268.  
  269.     
  270.     def about(self):
  271.         text = '\nAuthor: %r\nPy Version: %s\nPy Shell Revision: %s\nPy Interpreter Revision: %s\nPython Version: %s\nwxPython Version: %s\nwxPython PlatformInfo: %s\nPlatform: %s' % (__author__, VERSION, self.revision, self.interp.revision, sys.version.split()[0], wx.VERSION_STRING, str(wx.PlatformInfo), sys.platform)
  272.         self.write(text.strip())
  273.  
  274.     
  275.     def OnChar(self, event):
  276.         if self.noteMode:
  277.             event.Skip()
  278.             return None
  279.         
  280.         if not self.CanEdit():
  281.             return None
  282.         
  283.         key = event.GetKeyCode()
  284.         currpos = self.GetCurrentPos()
  285.         stoppos = self.promptPosEnd
  286.         if key in [
  287.             wx.WXK_RETURN,
  288.             wx.WXK_NUMPAD_ENTER]:
  289.             pass
  290.         elif key in self.autoCompleteKeys:
  291.             if self.AutoCompActive():
  292.                 self.AutoCompCancel()
  293.             
  294.             command = self.GetTextRange(stoppos, currpos) + chr(key)
  295.             self.write(chr(key))
  296.             if self.autoComplete:
  297.                 self.autoCompleteShow(command)
  298.             
  299.         elif key == ord('('):
  300.             if self.AutoCompActive():
  301.                 self.AutoCompCancel()
  302.             
  303.             self.ReplaceSelection('')
  304.             command = self.GetTextRange(stoppos, currpos) + '('
  305.             self.write('(')
  306.             self.autoCallTipShow(command, self.GetCurrentPos() == self.GetTextLength())
  307.         else:
  308.             event.Skip()
  309.  
  310.     
  311.     def OnKeyDown(self, event):
  312.         key = event.GetKeyCode()
  313.         if self.AutoCompActive():
  314.             event.Skip()
  315.             return None
  316.         
  317.         controlDown = event.ControlDown()
  318.         altDown = event.AltDown()
  319.         shiftDown = event.ShiftDown()
  320.         currpos = self.GetCurrentPos()
  321.         endpos = self.GetTextLength()
  322.         selecting = self.GetSelectionStart() != self.GetSelectionEnd()
  323.         if controlDown and shiftDown and key in (ord('F'), ord('f')):
  324.             li = self.GetCurrentLine()
  325.             m = self.MarkerGet(li)
  326.             if m & 1:
  327.                 startP = self.PositionFromLine(li)
  328.                 self.MarkerDelete(li, 0)
  329.                 maxli = self.GetLineCount()
  330.                 li += 1
  331.                 li0 = li
  332.                 while li < maxli and self.GetLineVisible(li) == 0:
  333.                     li += 1
  334.                 endP = self.GetLineEndPosition(li - 1)
  335.                 self.ShowLines(li0, li - 1)
  336.                 self.SetSelection(startP, endP)
  337.                 return None
  338.             
  339.             (startP, endP) = self.GetSelection()
  340.             endP -= 1
  341.             startL = self.LineFromPosition(startP)
  342.             endL = self.LineFromPosition(endP)
  343.             if endL == self.LineFromPosition(self.promptPosEnd):
  344.                 endL -= 1
  345.             
  346.             m = self.MarkerGet(startL)
  347.             self.MarkerAdd(startL, 0)
  348.             self.HideLines(startL + 1, endL)
  349.             self.SetCurrentPos(startP)
  350.         
  351.         if False and key == wx.WXK_F12:
  352.             if self.noteMode:
  353.                 self.promptPosEnd = self.PositionFromLine(self.GetLineCount() - 1) + len(str(sys.ps1))
  354.                 self.GotoLine(self.GetLineCount())
  355.                 self.GotoPos(self.promptPosEnd)
  356.                 self.prompt()
  357.                 self.SetCaretForeground('black')
  358.                 self.SetCaretWidth(1)
  359.                 self.SetCaretPeriod(500)
  360.             else:
  361.                 self.SetCaretForeground('red')
  362.                 self.SetCaretWidth(4)
  363.                 self.SetCaretPeriod(0)
  364.             self.noteMode = not (self.noteMode)
  365.             return None
  366.         
  367.         if self.noteMode:
  368.             event.Skip()
  369.             return None
  370.         
  371.         if (not controlDown and not shiftDown or not altDown) and key in [
  372.             wx.WXK_RETURN,
  373.             wx.WXK_NUMPAD_ENTER]:
  374.             if self.CallTipActive():
  375.                 self.CallTipCancel()
  376.             
  377.             self.processLine()
  378.         elif shiftDown and key in [
  379.             wx.WXK_RETURN,
  380.             wx.WXK_NUMPAD_ENTER]:
  381.             self.OnShowCompHistory()
  382.         elif controlDown and key in [
  383.             wx.WXK_RETURN,
  384.             wx.WXK_NUMPAD_ENTER]:
  385.             if self.CallTipActive():
  386.                 self.CallTipCancel()
  387.             
  388.             if currpos == endpos:
  389.                 self.processLine()
  390.             else:
  391.                 self.insertLineBreak()
  392.         elif controlDown and altDown:
  393.             event.Skip()
  394.         elif key == wx.WXK_ESCAPE:
  395.             if self.CallTipActive():
  396.                 event.Skip()
  397.             else:
  398.                 self.clearCommand()
  399.         elif key == wx.WXK_BACK and controlDown and shiftDown:
  400.             self.clearCommand()
  401.         elif controlDown and key in (ord(']'), wx.WXK_NUMPAD_ADD):
  402.             dispatcher.send(signal = 'FontIncrease')
  403.         elif controlDown and key in (ord('['), wx.WXK_NUMPAD_SUBTRACT):
  404.             dispatcher.send(signal = 'FontDecrease')
  405.         elif controlDown and key in (ord('='), wx.WXK_NUMPAD_DIVIDE):
  406.             dispatcher.send(signal = 'FontDefault')
  407.         elif (controlDown or key in (ord('X'), ord('x')) or shiftDown) and key == wx.WXK_DELETE:
  408.             self.Cut()
  409.         elif controlDown and not shiftDown and key in (ord('C'), ord('c'), wx.WXK_INSERT):
  410.             self.Copy()
  411.         elif controlDown and shiftDown and key in (ord('C'), ord('c'), wx.WXK_INSERT):
  412.             self.CopyWithPrompts()
  413.         elif altDown and not controlDown and key in (ord('C'), ord('c'), wx.WXK_INSERT):
  414.             self.CopyWithPromptsPrefixed()
  415.         elif key == wx.WXK_HOME:
  416.             home = self.promptPosEnd
  417.             if currpos > home:
  418.                 self.SetCurrentPos(home)
  419.                 if not selecting and not shiftDown:
  420.                     self.SetAnchor(home)
  421.                     self.EnsureCaretVisible()
  422.                 
  423.             else:
  424.                 event.Skip()
  425.         elif selecting and key not in NAVKEYS and not self.CanEdit():
  426.             pass
  427.         elif (controlDown and not shiftDown or key in (ord('V'), ord('v')) or shiftDown) and not controlDown and key == wx.WXK_INSERT:
  428.             self.Paste()
  429.         elif controlDown and key == wx.WXK_SPACE:
  430.             self.OnCallTipAutoCompleteManually(shiftDown)
  431.         elif controlDown and shiftDown and key in (ord('V'), ord('v')):
  432.             self.PasteAndRun()
  433.         elif (controlDown or key == wx.WXK_UP or altDown) and key in (ord('P'), ord('p')):
  434.             self.OnHistoryReplace(step = +1)
  435.         elif (controlDown or key == wx.WXK_DOWN or altDown) and key in (ord('N'), ord('n')):
  436.             self.OnHistoryReplace(step = -1)
  437.         elif (shiftDown or key == wx.WXK_UP) and self.CanEdit():
  438.             self.OnHistoryInsert(step = +1)
  439.         elif (shiftDown or key == wx.WXK_DOWN) and self.CanEdit():
  440.             self.OnHistoryInsert(step = -1)
  441.         elif key == wx.WXK_F8:
  442.             self.OnHistorySearch()
  443.         elif key == wx.WXK_BACK:
  444.             if selecting and self.CanEdit():
  445.                 event.Skip()
  446.             elif currpos > self.promptPosEnd:
  447.                 event.Skip()
  448.             
  449.         elif key in (wx.WXK_TAB, wx.WXK_DELETE):
  450.             if self.CanEdit():
  451.                 event.Skip()
  452.             
  453.         elif key == wx.WXK_INSERT:
  454.             pass
  455.         elif controlDown and key in (ord('L'), ord('l')):
  456.             pass
  457.         elif controlDown and key in (ord('T'), ord('t')):
  458.             pass
  459.         elif key in NAVKEYS:
  460.             event.Skip()
  461.         elif not self.CanEdit():
  462.             pass
  463.         else:
  464.             event.Skip()
  465.  
  466.     
  467.     def OnShowCompHistory(self):
  468.         his = self.history[:]
  469.         joined = ' '.join(his)
  470.         import re as re
  471.         newlist = re.split('[ \\.\\[\\]=}(\\)\\,0-9"]', joined)
  472.         thlist = []
  473.         for i in newlist:
  474.             if len(i) > 1:
  475.                 thlist.append(i)
  476.                 continue
  477.         
  478.         unlist = _[1]
  479.         unlist.sort((lambda a, b: cmp(a.lower(), b.lower())))
  480.         self.AutoCompSetIgnoreCase(True)
  481.         stringlist = ' '.join(unlist)
  482.         cpos = self.GetCurrentPos() - 1
  483.         while chr(self.GetCharAt(cpos)).isalnum():
  484.             cpos -= 1
  485.             continue
  486.             []
  487.         self.AutoCompShow(self.GetCurrentPos() - cpos - 1, stringlist)
  488.  
  489.     
  490.     def clearCommand(self):
  491.         startpos = self.promptPosEnd
  492.         endpos = self.GetTextLength()
  493.         self.SetSelection(startpos, endpos)
  494.         self.ReplaceSelection('')
  495.         self.more = False
  496.  
  497.     
  498.     def OnHistoryReplace(self, step):
  499.         self.clearCommand()
  500.         self.replaceFromHistory(step)
  501.  
  502.     
  503.     def replaceFromHistory(self, step):
  504.         ps2 = str(sys.ps2)
  505.         self.ReplaceSelection('')
  506.         newindex = self.historyIndex + step
  507.         if newindex <= newindex:
  508.             pass
  509.         elif newindex <= len(self.history):
  510.             self.historyIndex = newindex
  511.         
  512.         if newindex <= newindex:
  513.             pass
  514.         elif newindex <= len(self.history) - 1:
  515.             command = self.history[self.historyIndex]
  516.             command = command.replace('\n', os.linesep + ps2)
  517.             self.ReplaceSelection(command)
  518.         
  519.  
  520.     
  521.     def OnHistoryInsert(self, step):
  522.         if not self.CanEdit():
  523.             return None
  524.         
  525.         startpos = self.GetCurrentPos()
  526.         self.replaceFromHistory(step)
  527.         endpos = self.GetCurrentPos()
  528.         self.SetSelection(endpos, startpos)
  529.  
  530.     
  531.     def OnHistorySearch(self):
  532.         if not self.CanEdit():
  533.             return None
  534.         
  535.         startpos = self.GetCurrentPos()
  536.         numCharsAfterCursor = self.GetTextLength() - startpos
  537.         searchText = self.getCommand(rstrip = False)
  538.         if numCharsAfterCursor > 0:
  539.             searchText = searchText[:-numCharsAfterCursor]
  540.         
  541.         if not searchText:
  542.             return None
  543.         
  544.         if self.historyIndex <= -1 or self.historyIndex >= len(self.history) - 2:
  545.             searchOrder = range(len(self.history))
  546.         else:
  547.             searchOrder = range(self.historyIndex + 1, len(self.history)) + range(self.historyIndex)
  548.         for i in searchOrder:
  549.             command = self.history[i]
  550.             if command[:len(searchText)] == searchText:
  551.                 self.ReplaceSelection(command[len(searchText):])
  552.                 endpos = self.GetCurrentPos()
  553.                 self.SetSelection(endpos, startpos)
  554.                 self.historyIndex = i
  555.                 break
  556.                 continue
  557.         
  558.  
  559.     
  560.     def setStatusText(self, text):
  561.         print text
  562.  
  563.     
  564.     def insertLineBreak(self):
  565.         if self.CanEdit():
  566.             self.write(os.linesep)
  567.             self.more = True
  568.             self.prompt()
  569.         
  570.  
  571.     
  572.     def processLine(self):
  573.         thepos = self.GetCurrentPos()
  574.         startpos = self.promptPosEnd
  575.         endpos = self.GetTextLength()
  576.         ps2 = str(sys.ps2)
  577.         if self.CanEdit():
  578.             self.SetCurrentPos(endpos)
  579.             self.interp.more = False
  580.             command = self.GetTextRange(startpos, endpos)
  581.             lines = command.split(os.linesep + ps2)
  582.             lines = [ line.rstrip() for line in lines ]
  583.             command = '\n'.join(lines)
  584.             if self.reader.isreading:
  585.                 self.reader.input = command
  586.                 self.write(os.linesep)
  587.             else:
  588.                 self.push(command)
  589.                 wx.FutureCall(1, self.EnsureCaretVisible)
  590.         elif self.getCommand(rstrip = False):
  591.             command = self.getMultilineCommand()
  592.             self.clearCommand()
  593.             self.write(command)
  594.         else:
  595.             self.SetCurrentPos(thepos)
  596.             self.SetAnchor(thepos)
  597.  
  598.     
  599.     def getMultilineCommand(self, rstrip = True):
  600.         ps1 = str(sys.ps1)
  601.         ps1size = len(ps1)
  602.         ps2 = str(sys.ps2)
  603.         ps2size = len(ps2)
  604.         text = self.GetCurLine()[0]
  605.         line = self.GetCurrentLine()
  606.         while text[:ps2size] == ps2 and line > 0:
  607.             line -= 1
  608.             self.GotoLine(line)
  609.             text = self.GetCurLine()[0]
  610.         if text[:ps1size] == ps1:
  611.             line = self.GetCurrentLine()
  612.             self.GotoLine(line)
  613.             startpos = self.GetCurrentPos() + ps1size
  614.             line += 1
  615.             self.GotoLine(line)
  616.             while self.GetCurLine()[0][:ps2size] == ps2:
  617.                 line += 1
  618.                 self.GotoLine(line)
  619.             stoppos = self.GetCurrentPos()
  620.             command = self.GetTextRange(startpos, stoppos)
  621.             command = command.replace(os.linesep + ps2, '\n')
  622.             command = command.rstrip()
  623.             command = command.replace('\n', os.linesep + ps2)
  624.         else:
  625.             command = ''
  626.         if rstrip:
  627.             command = command.rstrip()
  628.         
  629.         return command
  630.  
  631.     
  632.     def getCommand(self, text = None, rstrip = True):
  633.         if not text:
  634.             text = self.GetCurLine()[0]
  635.         
  636.         command = self.lstripPrompt(text)
  637.         if command == text:
  638.             command = ''
  639.         
  640.         if rstrip:
  641.             command = command.rstrip()
  642.         
  643.         return command
  644.  
  645.     
  646.     def lstripPrompt(self, text):
  647.         ps1 = str(sys.ps1)
  648.         ps1size = len(ps1)
  649.         ps2 = str(sys.ps2)
  650.         ps2size = len(ps2)
  651.         if text[:ps1size] == ps1:
  652.             text = text[ps1size:]
  653.         elif text[:ps2size] == ps2:
  654.             text = text[ps2size:]
  655.         
  656.         return text
  657.  
  658.     
  659.     def push(self, command, silent = False):
  660.         if not silent:
  661.             self.write(os.linesep)
  662.         
  663.         busy = wx.BusyCursor()
  664.         self.waiting = True
  665.         self.more = self.interp.push(command)
  666.         self.waiting = False
  667.         del busy
  668.         if not self.more:
  669.             self.addHistory(command.rstrip())
  670.         
  671.         if not silent:
  672.             self.prompt()
  673.         
  674.  
  675.     
  676.     def addHistory(self, command):
  677.         self.historyIndex = -1
  678.         if command != '':
  679.             if len(self.history) == 0 or command != self.history[0]:
  680.                 self.history.insert(0, command)
  681.                 dispatcher.send(signal = 'Shell.addHistory', command = command)
  682.             
  683.  
  684.     
  685.     def write(self, text):
  686.         text = self.fixLineEndings(text)
  687.         self.AddText(text)
  688.         self.EnsureCaretVisible()
  689.  
  690.     
  691.     def fixLineEndings(self, text):
  692.         lines = text.split('\r\n')
  693.         for l in range(len(lines)):
  694.             chunks = lines[l].split('\r')
  695.             for c in range(len(chunks)):
  696.                 chunks[c] = os.linesep.join(chunks[c].split('\n'))
  697.             
  698.             lines[l] = os.linesep.join(chunks)
  699.         
  700.         text = os.linesep.join(lines)
  701.         return text
  702.  
  703.     
  704.     def prompt(self):
  705.         isreading = self.reader.isreading
  706.         skip = False
  707.         if isreading:
  708.             prompt = str(sys.ps3)
  709.         elif self.more:
  710.             prompt = str(sys.ps2)
  711.         else:
  712.             prompt = str(sys.ps1)
  713.         pos = self.GetCurLine()[1]
  714.         if pos > 0:
  715.             if isreading:
  716.                 skip = True
  717.             else:
  718.                 self.write(os.linesep)
  719.         
  720.         if not self.more:
  721.             self.promptPosStart = self.GetCurrentPos()
  722.         
  723.         if not skip:
  724.             self.write(prompt)
  725.         
  726.         if not self.more:
  727.             self.promptPosEnd = self.GetCurrentPos()
  728.             self.EmptyUndoBuffer()
  729.         
  730.         if self.more:
  731.             self.write('    ')
  732.         
  733.         self.EnsureCaretVisible()
  734.         self.ScrollToColumn(0)
  735.  
  736.     
  737.     def readline(self):
  738.         input = ''
  739.         reader = self.reader
  740.         reader.isreading = True
  741.         self.prompt()
  742.         
  743.         try:
  744.             while not reader.input:
  745.                 wx.YieldIfNeeded()
  746.             input = reader.input
  747.         finally:
  748.             reader.input = ''
  749.             reader.isreading = False
  750.  
  751.         input = str(input)
  752.         return input
  753.  
  754.     
  755.     def readlines(self):
  756.         lines = []
  757.         while lines[-1:] != [
  758.             '\n']:
  759.             lines.append(self.readline())
  760.         return lines
  761.  
  762.     
  763.     def raw_input(self, prompt = ''):
  764.         if prompt:
  765.             self.write(prompt)
  766.         
  767.         return self.readline()
  768.  
  769.     
  770.     def ask(self, prompt = 'Please enter your response:'):
  771.         dialog = wx.TextEntryDialog(None, prompt, 'Input Dialog (Raw)', '')
  772.         
  773.         try:
  774.             if dialog.ShowModal() == wx.ID_OK:
  775.                 text = dialog.GetValue()
  776.                 return text
  777.         finally:
  778.             dialog.Destroy()
  779.  
  780.         return ''
  781.  
  782.     
  783.     def pause(self):
  784.         self.ask('Press enter to continue:')
  785.  
  786.     
  787.     def clear(self):
  788.         self.ClearAll()
  789.  
  790.     
  791.     def run(self, command, prompt = True, verbose = True):
  792.         endpos = self.GetTextLength()
  793.         self.SetCurrentPos(endpos)
  794.         command = command.rstrip()
  795.         if prompt:
  796.             self.prompt()
  797.         
  798.         if verbose:
  799.             self.write(command)
  800.         
  801.         self.push(command)
  802.  
  803.     
  804.     def runfile(self, filename):
  805.         file = open(filename)
  806.         
  807.         try:
  808.             self.prompt()
  809.             for command in file.readlines():
  810.                 if command[:6] == 'shell.':
  811.                     self.run(command, prompt = False, verbose = False)
  812.                     continue
  813.                 self.run(command, prompt = False, verbose = True)
  814.         finally:
  815.             file.close()
  816.  
  817.  
  818.     
  819.     def autoCompleteShow(self, command, offset = 0):
  820.         self.AutoCompSetAutoHide(self.autoCompleteAutoHide)
  821.         self.AutoCompSetIgnoreCase(self.autoCompleteCaseInsensitive)
  822.         list = self.interp.getAutoCompleteList(command, includeMagic = self.autoCompleteIncludeMagic, includeSingle = self.autoCompleteIncludeSingle, includeDouble = self.autoCompleteIncludeDouble)
  823.         if list:
  824.             options = ' '.join(list)
  825.             self.AutoCompShow(offset, options)
  826.         
  827.  
  828.     
  829.     def autoCallTipShow(self, command, insertcalltip = True, forceCallTip = False):
  830.         if self.CallTipActive():
  831.             self.CallTipCancel()
  832.         
  833.         (name, argspec, tip) = self.interp.getCallTip(command)
  834.         if tip:
  835.             dispatcher.send(signal = 'Shell.calltip', sender = self, calltip = tip)
  836.         
  837.         if not (self.autoCallTip) and not forceCallTip:
  838.             return None
  839.         
  840.         if argspec and insertcalltip and self.callTipInsert:
  841.             startpos = self.GetCurrentPos()
  842.             self.write(argspec + ')')
  843.             endpos = self.GetCurrentPos()
  844.             self.SetSelection(endpos, startpos)
  845.         
  846.         if tip:
  847.             curpos = self.GetCurrentPos()
  848.             tippos = curpos - len(name) + 1
  849.             fallback = curpos - self.GetColumn(curpos)
  850.             tippos = max(tippos, fallback)
  851.             self.CallTipShow(tippos, tip)
  852.         
  853.  
  854.     
  855.     def OnCallTipAutoCompleteManually(self, shiftDown):
  856.         if self.AutoCompActive():
  857.             self.AutoCompCancel()
  858.         
  859.         currpos = self.GetCurrentPos()
  860.         stoppos = self.promptPosEnd
  861.         cpos = currpos
  862.         pointavailpos = -1
  863.         while cpos >= stoppos:
  864.             if self.GetCharAt(cpos) == ord('.'):
  865.                 pointavailpos = cpos
  866.                 break
  867.             
  868.             cpos -= 1
  869.         if pointavailpos != -1:
  870.             textbehind = self.GetTextRange(pointavailpos + 1, currpos)
  871.             pointavailpos += 1
  872.             if not shiftDown:
  873.                 stoppos = self.promptPosEnd
  874.                 textbefore = self.GetTextRange(stoppos, pointavailpos)
  875.                 self.autoCompleteShow(textbefore, len(textbehind))
  876.             else:
  877.                 cpos = pointavailpos
  878.                 begpos = -1
  879.                 while cpos > stoppos:
  880.                     if chr(self.GetCharAt(cpos)).isspace():
  881.                         begpos = cpos
  882.                         break
  883.                     
  884.                     cpos -= 1
  885.                 if begpos == -1:
  886.                     begpos = cpos
  887.                 
  888.                 ctips = self.GetTextRange(begpos, currpos)
  889.                 ctindex = ctips.find('(')
  890.                 if ctindex != -1 and not self.CallTipActive():
  891.                     if self.GetCharAt(currpos - 1) == ord('('):
  892.                         pass
  893.                     self.autoCallTipShow(ctips[:ctindex + 1], self.GetCurrentPos() == self.GetTextLength(), True)
  894.                 
  895.         
  896.  
  897.     
  898.     def writeOut(self, text):
  899.         self.write(text)
  900.  
  901.     
  902.     def writeErr(self, text):
  903.         self.write(text)
  904.  
  905.     
  906.     def redirectStdin(self, redirect = True):
  907.         if redirect:
  908.             sys.stdin = self.reader
  909.         else:
  910.             sys.stdin = self.stdin
  911.  
  912.     
  913.     def redirectStdout(self, redirect = True):
  914.         if redirect:
  915.             sys.stdout = PseudoFileOut(self.writeOut)
  916.         else:
  917.             sys.stdout = self.stdout
  918.  
  919.     
  920.     def redirectStderr(self, redirect = True):
  921.         if redirect:
  922.             sys.stderr = PseudoFileErr(self.writeErr)
  923.         else:
  924.             sys.stderr = self.stderr
  925.  
  926.     
  927.     def CanCut(self):
  928.         if self.GetSelectionStart() != self.GetSelectionEnd() and self.GetSelectionStart() >= self.promptPosEnd and self.GetSelectionEnd() >= self.promptPosEnd:
  929.             return True
  930.         else:
  931.             return False
  932.  
  933.     
  934.     def CanPaste(self):
  935.         if self.CanEdit() and editwindow.EditWindow.CanPaste(self):
  936.             return True
  937.         else:
  938.             return False
  939.  
  940.     
  941.     def CanEdit(self):
  942.         if self.GetSelectionStart() != self.GetSelectionEnd():
  943.             if self.GetSelectionStart() >= self.promptPosEnd and self.GetSelectionEnd() >= self.promptPosEnd:
  944.                 return True
  945.             else:
  946.                 return False
  947.         else:
  948.             return self.GetCurrentPos() >= self.promptPosEnd
  949.  
  950.     
  951.     def Cut(self):
  952.         if self.CanCut() and self.CanCopy():
  953.             if self.AutoCompActive():
  954.                 self.AutoCompCancel()
  955.             
  956.             if self.CallTipActive():
  957.                 self.CallTipCancel()
  958.             
  959.             self.Copy()
  960.             self.ReplaceSelection('')
  961.         
  962.  
  963.     
  964.     def Copy(self):
  965.         if self.CanCopy():
  966.             ps1 = str(sys.ps1)
  967.             ps2 = str(sys.ps2)
  968.             command = self.GetSelectedText()
  969.             command = command.replace(os.linesep + ps2, os.linesep)
  970.             command = command.replace(os.linesep + ps1, os.linesep)
  971.             command = self.lstripPrompt(text = command)
  972.             data = wx.TextDataObject(command)
  973.             self._clip(data)
  974.         
  975.  
  976.     
  977.     def CopyWithPrompts(self):
  978.         if self.CanCopy():
  979.             command = self.GetSelectedText()
  980.             data = wx.TextDataObject(command)
  981.             self._clip(data)
  982.         
  983.  
  984.     
  985.     def CopyWithPromptsPrefixed(self):
  986.         if self.CanCopy():
  987.             command = self.GetSelectedText()
  988.             spaces = '    '
  989.             command = spaces + command.replace(os.linesep, os.linesep + spaces)
  990.             data = wx.TextDataObject(command)
  991.             self._clip(data)
  992.         
  993.  
  994.     
  995.     def _clip(self, data):
  996.         if wx.TheClipboard.Open():
  997.             wx.TheClipboard.UsePrimarySelection(False)
  998.             wx.TheClipboard.SetData(data)
  999.             wx.TheClipboard.Flush()
  1000.             wx.TheClipboard.Close()
  1001.         
  1002.  
  1003.     
  1004.     def Paste(self):
  1005.         if self.CanPaste() and wx.TheClipboard.Open():
  1006.             ps2 = str(sys.ps2)
  1007.             if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  1008.                 data = wx.TextDataObject()
  1009.                 if wx.TheClipboard.GetData(data):
  1010.                     self.ReplaceSelection('')
  1011.                     command = data.GetText()
  1012.                     command = command.rstrip()
  1013.                     command = self.fixLineEndings(command)
  1014.                     command = self.lstripPrompt(text = command)
  1015.                     command = command.replace(os.linesep + ps2, '\n')
  1016.                     command = command.replace(os.linesep, '\n')
  1017.                     command = command.replace('\n', os.linesep + ps2)
  1018.                     self.write(command)
  1019.                 
  1020.             
  1021.             wx.TheClipboard.Close()
  1022.         
  1023.  
  1024.     
  1025.     def PasteAndRun(self):
  1026.         text = ''
  1027.         if wx.TheClipboard.Open():
  1028.             if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_TEXT)):
  1029.                 data = wx.TextDataObject()
  1030.                 if wx.TheClipboard.GetData(data):
  1031.                     text = data.GetText()
  1032.                 
  1033.             
  1034.             wx.TheClipboard.Close()
  1035.         
  1036.         if text:
  1037.             self.Execute(text)
  1038.         
  1039.  
  1040.     
  1041.     def Execute(self, text):
  1042.         ps1 = str(sys.ps1)
  1043.         ps2 = str(sys.ps2)
  1044.         endpos = self.GetTextLength()
  1045.         self.SetCurrentPos(endpos)
  1046.         startpos = self.promptPosEnd
  1047.         self.SetSelection(startpos, endpos)
  1048.         self.ReplaceSelection('')
  1049.         text = text.lstrip()
  1050.         text = self.fixLineEndings(text)
  1051.         text = self.lstripPrompt(text)
  1052.         text = text.replace(os.linesep + ps1, '\n')
  1053.         text = text.replace(os.linesep + ps2, '\n')
  1054.         text = text.replace(os.linesep, '\n')
  1055.         lines = text.split('\n')
  1056.         commands = []
  1057.         command = ''
  1058.         for line in lines:
  1059.             if line.strip() == ps2.strip():
  1060.                 line = ''
  1061.             
  1062.             lstrip = line.lstrip()
  1063.             if line.strip() != '' and lstrip == line and lstrip[:4] not in ('else', 'elif') and lstrip[:6] != 'except':
  1064.                 if command:
  1065.                     commands.append(command)
  1066.                 
  1067.                 command = line
  1068.                 continue
  1069.             command += '\n'
  1070.             command += line
  1071.         
  1072.         commands.append(command)
  1073.         for command in commands:
  1074.             command = command.replace('\n', os.linesep + ps2)
  1075.             self.write(command)
  1076.             self.processLine()
  1077.         
  1078.  
  1079.     
  1080.     def wrap(self, wrap = True):
  1081.         
  1082.         try:
  1083.             self.SetWrapMode(wrap)
  1084.         except AttributeError:
  1085.             return 'Wrapping is not available in this version.'
  1086.  
  1087.  
  1088.     
  1089.     def zoom(self, points = 0):
  1090.         self.SetZoom(points)
  1091.  
  1092.     
  1093.     def LoadSettings(self, config):
  1094.         self.autoComplete = config.ReadBool('Options/AutoComplete', True)
  1095.         self.autoCompleteIncludeMagic = config.ReadBool('Options/AutoCompleteIncludeMagic', True)
  1096.         self.autoCompleteIncludeSingle = config.ReadBool('Options/AutoCompleteIncludeSingle', True)
  1097.         self.autoCompleteIncludeDouble = config.ReadBool('Options/AutoCompleteIncludeDouble', True)
  1098.         self.autoCallTip = config.ReadBool('Options/AutoCallTip', True)
  1099.         self.callTipInsert = config.ReadBool('Options/CallTipInsert', True)
  1100.         self.SetWrapMode(config.ReadBool('View/WrapMode', True))
  1101.         useAA = config.ReadBool('Options/UseAntiAliasing', self.GetUseAntiAliasing())
  1102.         self.SetUseAntiAliasing(useAA)
  1103.         self.lineNumbers = config.ReadBool('View/ShowLineNumbers', True)
  1104.         self.setDisplayLineNumbers(self.lineNumbers)
  1105.         zoom = config.ReadInt('View/Zoom/Shell', -99)
  1106.         if zoom != -99:
  1107.             self.SetZoom(zoom)
  1108.         
  1109.  
  1110.     
  1111.     def SaveSettings(self, config):
  1112.         config.WriteBool('Options/AutoComplete', self.autoComplete)
  1113.         config.WriteBool('Options/AutoCompleteIncludeMagic', self.autoCompleteIncludeMagic)
  1114.         config.WriteBool('Options/AutoCompleteIncludeSingle', self.autoCompleteIncludeSingle)
  1115.         config.WriteBool('Options/AutoCompleteIncludeDouble', self.autoCompleteIncludeDouble)
  1116.         config.WriteBool('Options/AutoCallTip', self.autoCallTip)
  1117.         config.WriteBool('Options/CallTipInsert', self.callTipInsert)
  1118.         config.WriteBool('Options/UseAntiAliasing', self.GetUseAntiAliasing())
  1119.         config.WriteBool('View/WrapMode', self.GetWrapMode())
  1120.         config.WriteBool('View/ShowLineNumbers', self.lineNumbers)
  1121.         config.WriteInt('View/Zoom/Shell', self.GetZoom())
  1122.  
  1123.     
  1124.     def GetContextMenu(self):
  1125.         menu = wx.Menu()
  1126.         menu.Append(wx.ID_UNDO, 'Undo')
  1127.         menu.Append(wx.ID_REDO, 'Redo')
  1128.         menu.AppendSeparator()
  1129.         menu.Append(wx.ID_CUT, 'Cut')
  1130.         menu.Append(wx.ID_COPY, 'Copy')
  1131.         menu.Append(frame.ID_COPY_PLUS, 'Copy Plus')
  1132.         menu.Append(wx.ID_PASTE, 'Paste')
  1133.         menu.Append(frame.ID_PASTE_PLUS, 'Paste Plus')
  1134.         menu.Append(wx.ID_CLEAR, 'Clear')
  1135.         menu.AppendSeparator()
  1136.         menu.Append(wx.ID_SELECTALL, 'Select All')
  1137.         return menu
  1138.  
  1139.     
  1140.     def OnContextMenu(self, evt):
  1141.         menu = self.GetContextMenu()
  1142.         self.PopupMenu(menu)
  1143.  
  1144.     
  1145.     def OnUpdateUI(self, evt):
  1146.         id = evt.Id
  1147.         if id in (wx.ID_CUT, wx.ID_CLEAR):
  1148.             evt.Enable(self.CanCut())
  1149.         elif id in (wx.ID_COPY, frame.ID_COPY_PLUS):
  1150.             evt.Enable(self.CanCopy())
  1151.         elif id in (wx.ID_PASTE, frame.ID_PASTE_PLUS):
  1152.             evt.Enable(self.CanPaste())
  1153.         elif id == wx.ID_UNDO:
  1154.             evt.Enable(self.CanUndo())
  1155.         elif id == wx.ID_REDO:
  1156.             evt.Enable(self.CanRedo())
  1157.         
  1158.  
  1159.  
  1160.